package com.cdgc.web.controller;

import com.cdgc.web.pojo.UserTable;
import com.cdgc.web.pojo.Userdata;
import com.cdgc.web.service.UserService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.swing.text.html.HTML;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService userService;


    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/doLogin")
    public String doLogin(String username, String password, HttpSession session, Model model){

        if(username==null||username.equals("")||password==null||password.equals("")){
            model.addAttribute("errorMsg","用户名或密码不能为空！");
            return "login";
        }
        Userdata userdata = userService.doLogin(username, password);
        if (userdata!=null){
            session.setAttribute("user",userdata);
            return "index";
        }else {
            model.addAttribute("errorMsg","用户名或密码错误！");
            return "login";
        }
    }

    @RequestMapping("/loginOut")
    public String loginOut(HttpSession session){

        return "redirect:/login";
    }

    @RequestMapping("/queryUsers")
    public ModelAndView queryUsers(){
        List<UserTable> userTableList = userService.queryUsers();
        ModelAndView mv = new ModelAndView();
        mv.addObject("userTableList",userTableList);
        mv.setViewName("usertable");
        return mv;
    }

    @RequestMapping("/addUser")
    public String addUser(UserTable userTable){
        userService.addUser(userTable);
        return "redirect:/queryUsers";
    }

    @RequestMapping("/ModelAndView")
    public ModelAndView toUpdateUser(Integer id){
        UserTable userTable = userService.queryUserById(id);
        ModelAndView mv = new ModelAndView();
        mv.addObject("userTable",userTable);
        mv.setViewName("updateUser");
        //todo
        return null;
    }
    @RequestMapping("updateUser")
    public String updateUser(UserTable userTable){
        userService.updateUser(userTable);
        return "redirect:/queryUsers";
    }

    @RequestMapping("deleteUserById")
    public String deleteUserById(Integer id){
        userService.deleteUserById(id);
        return "redirect:/queryUsers";
    }
}
